package com.hydra.framework.event.kvo.helper;

import com.hydra.framework.event.kvo.Kvo;
import com.hydra.framework.event.kvo.KvoSource;

import java.util.HashMap;
import java.util.Map.Entry;

public class KvoBinder {

    private Object mTarget;

    private HashMap<String, KvoSource> mKvoSources = new HashMap<String, KvoSource>();

    public KvoBinder(Object target) {
        mTarget = target;
    }

    /**
     * 直接以source的class name 当作key
     */
    public boolean singleBindSourceTo(KvoSource source) {
        if (source != null) {
            return singleBindSourceTo(source.getClass().getSimpleName(), source);
        }
        return false;
    }

    public synchronized boolean singleBindSourceTo(String name, KvoSource source) {
        KvoSource oldSource = mKvoSources.get(name);

        //注意，这里用了==而没有用equals
        if (oldSource == source) {
            return false;
        }

        if (oldSource != null) {
            Kvo.autoUnbindingFrom(oldSource, mTarget);
        }

        if (source != null) {
            Kvo.autoBindingTo(source, mTarget);
        }

        mKvoSources.put(name, source);

        return true;
    }

    public synchronized void clearKvoConnection(String name) {
        KvoSource source = mKvoSources.remove(name);
        if (source != null) {
            Kvo.autoUnbindingFrom(source, mTarget);
        }
    }

    public synchronized void clearAllKvoConnections() {
        if (mKvoSources.size() > 0) {
            for (Entry<String, KvoSource> entry : mKvoSources.entrySet()) {
                KvoSource value = entry.getValue();
                if (value != null) {
                    Kvo.autoUnbindingFrom(value, mTarget);
                }
            }
            mKvoSources.clear();
        }
    }
}
